package main

import (
	"fmt"
)

func main() {
	fmt.Println(myAtoi("-91283472332"))
}

func myAtoi(s string) int {
	skip := 0
	for _, c := range s {
		if c == ' ' {
			skip++
		} else {
			break
		}
	}
	s = s[skip:]

	if s == "" {
		return 0
	}

	// Pick off leading sign.
	neg := false
	if s[0] == '+' {
		s = s[1:]
	} else if s[0] == '-' {
		neg = true
		s = s[1:]
	} else if !(s[0]-'0' >= 0 && s[0]-'0' <= 9) {
		return 0
	}

	cutoff := uint32(1 << uint(31))

	// Convert unsigned and check range.
	var un uint32
	const maxU32 uint32 = 1<<32 - 1
	ucutOff := maxU32/10 + 1
	for _, c := range s {
		d := c - '0'
		if d >= 0 && d <= 9 {
			// 知道什么时候停止
			if un > ucutOff {
				un = maxU32
				break
			}
			un = un*10 + uint32(d)
		} else {
			break
		}
	}

	// 需要判断最后一位整体的情况
	if !neg && un >= cutoff {
		return int(cutoff - 1)
	}
	if neg && un > cutoff {
		return -int(cutoff)
	}
	n := int(un)
	if neg {
		n = -n
	}
	return n
}